package org.tinygroup.elmvel2;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.mvel2.MVEL;
import org.tinygroup.context.Context;
import org.tinygroup.context.Context2Map;
import org.tinygroup.el.EL;
import org.tinygroup.el.ElImportContainer;

public class Mvel2Impl implements EL {
	private Map<String, Serializable> cacheExpression = new HashMap<String, Serializable>();

	@SuppressWarnings("unchecked")
	public Object execute(String expression, Context context) {
		Serializable s = null;
		if (cacheExpression.containsKey(expression)) {
			s = cacheExpression.get(expression);
		} else if (ElImportContainer.getImports().isEmpty()) {
			s = MVEL.compileExpression(expression);
		} else {
			s = MVEL.compileExpression(expression,
					ElImportContainer.getImports());
		}
		Object result = MVEL.executeExpression(s, new Context2Map(context));
		if(s!=null){
			cacheExpression.put(expression, s);
		}
		return result;
	}

}
